<!-- 检测点管理 -->
<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template v-for="boxContent in contentList" :key="boxContent?.title">
        <PackageCard class="card" :boxContent="boxContent" />
      </template>
    </div>
    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"
        @handle-selection-change="handleSelectionChange"
        @handle-size-change="handleSizeChange"
        @handle-current-change="handleCurrentChange"
      >
      <template #statusText>
          <el-table-column
            show-overflow-tooltip
            :min-width="100"
            prop="statusText"
            label="状态"
            fit="true"
            show-header="true"
            align="left"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :class="scope.row.status ===  1 ? `point1` : scope.row.status ===  2 ? `point2`: 'point4'"></span>
                <span>{{ scope.row['statusText'] }}</span>
              </div>
            </template>
          </el-table-column>
        </template>
      </JqTable>
      <!-- <AddOrUpdate
        ref="addOrUpdateRef"
        :dialogDatas="dialogDatas"
        @clear-form-datas="clearFormDatas"
        @on-cancel="onCancel"
        @on-confirm="onConfirm"
      /> -->
      <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'CheckPoint' }); //检测点管理
import { reactive, ref, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
import { JqTable } from '@/components/Table/index';
import { useRouteStore } from '@/store';

import { AddOrUpdate } from './components';
import { PackageCard } from '@/components/PackageCard/index';
import type { FormInstance } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

import {
  getCheckPointsRequest,
  statisticseRequest,
  addCheckPointsRequest,
  pauseOrEffectiverRequest,
  editCheckPointsRequest,
  getCheckPointsDetailRequest,
  exportRequest
} from '@/api/checkPoint';
import { orgOptionsRequest, getEnumListRequest } from '@/api/common';
interface Row {
  id: number;
  status: number;
  checkPointsId: number;
  statusConfig:object
}
const showDialog = ref(false)
const router = useRouter();
const routeStore = useRouteStore();

let checkPointsOptionsDatas = reactive({}); //归属检测点下拉数据

let orgIdDatas = reactive([]); //归属组织下拉数据
let multipleSelection = reactive([]);
let searchFormParams = reactive({
  // deviceQueryReq: {}
}); //查询参数
let enumListDatas = reactive({}); //状态下拉数据（筛选）
let PointsStatusEnumDatas = reactive({}); //状态下拉数据(新增编辑查看)


const addOrUpdateRef = ref();
let currentClickRowDatas = ref(); //当前操作的表格明细

let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '检测点查询',
    placeholder: '请输入检测点查询',
    eName: 'pointName'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '检测点状态',
    options: () => {
      return enumListDatas;//待激活去掉
    },
    eName: 'status'
  },
  {
    type: 'input',
    value: '',
    label: '检测点ID',
    placeholder: '请输入检测点ID',
    eName: 'checkPointsId'
  },

  {
    type: 'cascader',
    value: '',
    label: '所在地区',
    eName: 'area',
    keys: ['provinceId', 'cityId', 'districtId']
  },

  {
    type: 'input',
    value: '',
    label: '地址',
    placeholder: '请输入地址',
    eName: 'detailedAddress'
  },
  {
    type: 'input',
    value: '',
    label: '负责人姓名',
    placeholder: '请输入负责人姓名',
    eName: 'responsiblePersonName'
  },
  {
    type: 'input',
    value: '',
    label: '负责人手机号',
    placeholder: '请输入负责人手机号',
    eName: 'responsiblePersonPhone'
  },
  {
    type: 'date',
    value: '',
    label: '创建时间',
    eName: 'createTime'
  }
]);
let dialogForConfigDatas = reactive([
  {
    type: 'input',
    value: '',
    label: '检测点ID',
    required: true,
    eName: 'id',
    placeholder:'请输入检测点ID',
    isHide:true
  },
  {
    type: 'input',
    value: '',
    label: '检测点名称',
    required: true,
    placeholder:'请输入检测点名称',
    eName: 'pointName',
  },

  {
    type: 'select',
    value: '',
    label: '归属组织机构',
    required: true,
    placeholder:'请输入归属组织机构',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '状态',
    required: true,
    placeholder:'请选择状态',
    options: () => {
      return PointsStatusEnumDatas;
    },
    eName: 'status'
  },
  {
    type: 'cascader',
    value: [],
    label: '所在地区',
    required: true,
    placeholder:'请选择状态',
    keys: ['provinceId', 'cityId', 'districtId'],
  },
  {
    type: 'input2',//输入文本限制
    value: '',
    label: '详细地址',
    required: true,
    placeholder:'请输入详细地址',
    eName: 'detailedAddress'
  },
  {
    type: 'input',
    value: '',
    label: '经纬度',
    required: true,
    placeholder:'请输入经纬度',
    eName: 'coordinates'
  },
  {
    type: 'input2',
    value: '',
    label: '负责人姓名',
    required: true,
    placeholder:'请输入负责人姓名',
    eName: 'responsiblePersonName'
  },
  {
    type: 'input3',//手机号校验
    value: '',
    label: '负责人手机号',
    required: true,
    placeholder:'请输入负责人手机号',
    eName: 'responsiblePersonPhone'
  }
]);
const tableColumn = reactive([
  //内置
  { label: '检测点ID', prop: 'id',minWidth: '90' },
  { label: '检测点名称', prop: 'pointName',minWidth: '100' },
  { label: '归属组织机构', prop: 'orgName',minWidth: '120' },
  { label: '所在地区', prop: 'area',minWidth: '80' },
  { label: '地址', prop: 'detailedAddress',minWidth: '80' },
  { label: '创建时间', prop: 'createTime',minWidth: '170' },
  { label: '最后一次检测时间', prop: 'lastCheckTime',minWidth: '170' },
  { label: '状态', prop: 'statusText',minWidth: '80',slot: true },
  { label: '负责人姓名', prop: 'responsiblePersonName',minWidth: '100' },
  { label: '负责人手机号', prop: 'responsiblePersonPhone',minWidth: '120' },
  { label: '健康顾问数', prop: 'healthDoctorCount',minWidth: '100' },
  { label: '设备数', prop: 'deviceCount',minWidth: '80' },
  { label: '已检测次数', prop: 'checkedCount',minWidth: '100' }
]);
let tableButtons = reactive([
  //来源于数据
  {
    id: 14,
    type: 'primary',
    label: '添加',
    perms: 'checkpoint:btn:create',
    onClick:async () => {
      showDialog.value = true
      dialogDatas = {
        title: '新增',
        type: 'add',
        datas: dialogForConfigDatas,
        enumListDatas:enumListDatas
      };
      getStatisticseRequest()
    }
  },
  {
    id: 18,
    type: '',
    label: '导出',
    perms: 'checkpoint:btn:export',
    onClick: async () => {
      const params=Object.assign({},searchFormParams,{pageNum: page.page, pageSize: page.pageSize })
      const data: any =  await exportRequest(params)
      if (data.code === 2000) {
        ElMessage.success('导出成功');
      }
      window.open(data.data);
    }
  },
]);
let itemsButtons = reactive([
  //来源于数据
  {
    id: 12,
    type: 'success',
    label: '查看',
    perms: 'checkpoint:btn:view',
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialog.value = true
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row,
        enumListDatas:enumListDatas
      };
    }
  },
  {
    id: 13,
    type: 'primary',
    label: '编辑',
    perms: 'checkpoint:btn:edit',
    onClick: (row: Row) => {
      showDialog.value = true
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row,
        enumListDatas:enumListDatas
      };
    }
  },
  {
    id: 15,
    eName: 'pause',
    buttonType:'switch',
    perms: 'checkpoint:btn:status',
    statusConfig:{
        1:'生效',
        2:'暂停',
        // 3:'待激活'
      },
    onClick: async (row: Row) => {
      // getEnableOrDisablDatas({ id: row.id, status: row.status === 1 ? 2 : 1 });
      await pauseOrEffectiverDatas({ checkPointsId: row.id, status: row.status===1?2:1  });
      getList();
      ElMessage.success('修改成功')
    }
  },
  {
    id: 16,
    perms: 'checkpoint:btn:del',
    type: 'warning',
    label: '删除',
    onClick: () => {
      alert(1);
    }
  }
]);

const contentList =reactive( [
  {
    title: '本月新增检测点',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '检测点总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '生效检测点',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  },
  {
    title: '暂停检测点',
    number: '',
    bgUrl: 'Bg4.png',
    iconUrl: 'Icon4.png'
  },
  {
    title: '待激活检测点',
    number: '',
    bgUrl: 'Bg5.png',
    iconUrl: 'Icon5.png'
  }
]);
const currentMenudatas = computed(() => routeStore.currentMenudatas);

const chanFormValue=(formParamsDatats:{})=>{
  searchFormParams=formParamsDatats
}
//设置弹出框内表单回显数据
const setDialogDefaultDatas = async (row: { id: number }) => {
  currentClickRowDatas.value = row;
  const data: any = await getCheckPointsDetailRequest({ checkPointsId: row.id });
  dialogForConfigDatas.forEach((d) => {
    if (d.type === 'cascader') {
      d.keys.forEach((key, i) => {
        d.value.push(data.data[key]?.toString());
      });
      return;
    }
    d.value = data.data[d.eName];
  });
};


const onAddOrUpdate = (data?: Recordable) => {
  addOrUpdateRef.value.init(data);
  addOrUpdateRef.value.handleDialog(true);

};
let dialogDatas = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getCheckPointsRequest,
    params: ()=>searchFormParams
  });
// const onCancel = () => {
//   //新增，查看，编辑弹出框按钮取消事件
//   clearFormDatas();
//   addOrUpdateRef.value.handleDialog(false);
// };
// const onConfirm =async (datas: {}, type: any) => {
//   // 新增，查看，编辑弹出框按钮确定事件
//   // multipleSelection = val;
//   let data=null

//   if (type === 'edit') {
//     //编辑
//     datas[dialogForConfigDatas[0].eName]=dialogForConfigDatas[0].value
//     data = await editCheckPointsRequest(datas);
//   } else {
//     //新增
//     data=await addCheckPointsRequest(datas);
//   }
//   if (data.code == 2000) {
//     const text=type === 'edit'?'编辑成功':'新增成功'
//         ElMessage.success(text);
//   }
//   clearFormDatas();
//   addOrUpdateRef.value.handleDialog(false);
//   getList();
// };
/* 表格多选事件 */
const handleSelectionChange = (val: []) => {
  multipleSelection = val;
};
/* 表单查询 */
const handleSearch = (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
};
// /*清除表单值 */
// const clearFormDatas = () => {
//   dialogForConfigDatas = dialogForConfigDatas.map((item) => {
//     if (item.value) {
//       if (item.type === 'cascader') {
//         item.value = [];
//       } else {
//         item.value = '';
//       }
//     }
//     return item;
//   });
// };

/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams={}
  searchForm = searchForm.map((item) => {
    if (item.value) {
      if (item.type === 'cascader') {
        item.value = [];
      } else {
        item.value = '';
      }
    }
    return item;
  });
 getList();

};
const updateList = () => {
  getList();
  getStatisticseRequest()
  showDialog.value = false
}


const getStatisticseRequest = async () => {
  const data: any = await statisticseRequest({});
  const statisticsDatas = data.data;
  contentList[0].number = statisticsDatas.newCheckPointsThisMonth;
  contentList[1].number = statisticsDatas.totalCheckPoints;
  contentList[2].number = statisticsDatas.activeCheckPoints;
  contentList[3].number = statisticsDatas.pausedCheckPoints;
  contentList[4].number = statisticsDatas.toActiveCheckPoints;

};
/* 获取归属检测点数据 */
// const getCheckPointsOptionsDatas = async () => {
//   const data: any = await getCheckPointsOptionsRequest({});
//   checkPointsOptionsDatas = data.data;
// };
/* 归属组织 */
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: false });
  orgIdDatas = data.data;
};
//根据数据返回按钮信息控制权限
/* params
{
  datas:本地配置的按钮数据（tableButtons/itemsButtons)
}
*/
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
/* 获取设备状态数据（筛选） */
const getEnumListDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'CheckPointsStatusEnum' });
  enumListDatas = data.data;
};


/* 获取设备状态数据（新增编辑） */
const getPointsStatusEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'PointsStatusEnum' });
  PointsStatusEnumDatas = data.data;
};


/*添加检测点 */
const addCheckPointsDatas = async (datas: {}) => {
  const data: any = await addCheckPointsRequest(datas);
};
/*停用/启用 */
const pauseOrEffectiverDatas = async (datas: {}) => {
  const data: any = await pauseOrEffectiverRequest(datas);
};

/*编辑检测点 */
const editCheckPointsRequestDatas = async (datas: {}) => {
  const data: any = await editCheckPointsRequest(datas);
};

onMounted(() => {
  getStatisticseRequest();
  // getCheckPointsOptionsDatas();
  getOrgOptionsDatas();
  getPointsStatusEnumDatas()
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
  getEnumListDatas();
});
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  > .card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom:10px;
    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
